<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\ArticleRequest;
use App\Models\Article;
use App\Models\Category;
use App\Models\Tag;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index(){
        $articles = Article::with(['tags','category'])->orderByDesc('id')->paginate(request('page_size', 10));
        return view('backend.article.index', compact('articles'));
    }

    public function create(){
        //dd(aetherupload_display_link('file_201912_457b47c7871dc0c3cfdef3050ef085e1.jpeg'));
        $categories = Category::all();
        $tags = Tag::all();
        return view('backend.article.create',compact('categories','tags'));
    }

    public function store(
        ArticleRequest $request,
        Article $article
    ){
        $article->fill($request->only([
            'title','category_id','page_image'
        ]))->save();
        //同步tag
        $article->tags()->sync($request->get('tags'));


        flash('文章添加成功', 'success');

        return back();
    }

    public function edit($id){
        $categories = Category::all();
        $tags = Tag::all();
        $article = Article::with(['tags','category'])->findOrFail($id);
        $article_tags = $article->tags->toArray();
        $article_tags = array_pluck($article_tags,'id');


        return view('backend.article.edit', compact( 'article','categories','tags','article_tags'));
    }

    public function update(
        ArticleRequest $request,
        $id
    ){
        $article = Article::findOrFail($id);
        $article->fill($request->only([
            'title','category_id','page_image'
        ]))->save();
        //同步tag
        $article->tags()->sync($request->get('tags'));

        flash('文章编辑成功', 'success');

        return back();
    }

    public function content($id){
        $article = Article::findOrFail($id);
        return view('backend.article.content',compact('article'));
    }

    public function setContent($id){
        $article = Article::findOrFail($id);
        $article->fill(request()->only(['content']))->save();
        flash('文章编辑成功', 'success');
        return back();
    }

    public function publish($id){
        $article = Article::findOrFail($id);
        //if (! $admin->couldDestroy()) {
        //    flash('当前用户是超级管理员账户无法删除');
        //} else {
        $article->fill(['is_draft'=>1])->save();
        flash('发布成功', 'success');
        //}

        return back();
    }

    public function destroy($id)
    {
        //TODO::判断该分类下是否有文章
        $article = Article::findOrFail($id);
        //if (! $admin->couldDestroy()) {
        //    flash('当前用户是超级管理员账户无法删除');
        //} else {
        $article->delete();
        flash('文章删除成功', 'success');
        //}

        return back();
    }
}
